package com.beaven.model.data.message;

import android.support.annotation.NonNull;
import com.beaven.model.data.BaseDbRepository;
import com.beaven.model.data.DbDataSource;
import com.beaven.model.model.db.Message;
import com.beaven.model.model.db.Message_Table;
import com.raizlabs.android.dbflow.sql.language.OperatorGroup;
import com.raizlabs.android.dbflow.sql.language.SQLite;
import com.raizlabs.android.dbflow.structure.database.transaction.QueryTransaction;
import java.util.Collections;
import java.util.List;

/**
 * author: Beaven
 * time: 2017/6/1 10:38
 */

public class MessageRepository extends BaseDbRepository<Message> implements DbDataSource<Message> {

  // 聊天的对象Id
  private String receiverId;
  private boolean isGroup;

  public MessageRepository(String receiverId, boolean isGroup) {
    super();
    this.receiverId = receiverId;
    this.isGroup = isGroup;
  }

  @Override public void load(SuccessCallBack<List<Message>> callBack) {
    super.load(callBack);

    if (isGroup) {
      SQLite.select()
          .from(Message.class)
          .where(Message_Table.receiveGroup_id.eq(receiverId))
          .orderBy(Message_Table.createAt, false)
          .limit(30)
          .async()
          .queryListResultCallback(this)
          .execute();
    } else {
      SQLite.select()
          .from(Message.class)
          .where(OperatorGroup.clause()
              .and(Message_Table.sender_id.eq(receiverId))
              .and(Message_Table.receiveGroup_id.isNull()))
          .or(Message_Table.receiver_id.eq(receiverId))
          .orderBy(Message_Table.createAt, false)
          .limit(30)
          .async()
          .queryListResultCallback(this)
          .execute();
    }
  }

  @Override
  public void onListQueryResult(QueryTransaction transaction, @NonNull List<Message> tResult) {
    // 反转返回的集合
    Collections.reverse(tResult);
    // 然后再调度
    super.onListQueryResult(transaction, tResult);
  }
}
